<template>
  <view class="page-container">
    <scroll-view
      scroll-y
      :refresher-enabled="true"
      @refresherrefresh="onRefresh"
      :refresher-triggered="isRefreshing"
      style="height: 100%; overflow-y: auto"
    >
      <!-- 搜索区域样式优化 -->

      <!-- <button @tap="getScanData('TOUT2025052100000003')">11</button> -->
      <view class="search-section">
        <view class="search-box">
          <my-picker
            class="search-input"
            label="出库单号"
            v-model="queryCode"
            type="radio"
            filterable
            clearable
            @confirm="selectOutSockChange"
          />
        </view>
      </view>

      <!-- Tabs样式优化 -->
      <wd-tabs v-model="tab" @tap="changeTabs">
        <wd-tab title="待出库">
          <view class="order-list">
            <view
              class="order-card"
              v-for="(item, index) in inSockProductData"
              :key="item.id"
              @tap="productDetail(item)"
            >
              <view class="card-header">
                <view class="order-info">
                  <text class="order-number">{{ item.code }}</text>
                  <view class="order-tag" type="warning" v-if="item.status === 2">待出库</view>
                  <view class="order-tag" type="warning" v-if="item.status === 4">部分出库</view>
                  <view class="order-tag" type="warning" v-if="item.status === 5">已完成</view>
                </view>
                <view class="order-time">
                  {{
                    outStockTypeList.filter((ele) => ele.codeValue == item.reason)?.[0]?.codeName ||
                    ''
                  }}
                </view>
              </view>
              <view class="card-content">
                <view class="product-list">
                  <view
                    class="product-info"
                    v-for="(product, productIndex) in item.stockTranDetailList"
                    :key="product.id"
                  >
                    <view class="product-details">
                      <view class="product-name">{{ product.productName }}</view>
                      <view class="product-quantity">
                        数量：{{ product.qty }}{{ formatUnit(product.unit) }}
                      </view>
                      <!-- <view class="location-info">
                        <wd-icon name="location" size="14" color="#666666"></wd-icon>
                        <text class="location-text">{{ product.location }}</text>
                      </view> -->
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <wd-loadmore custom-class="loadmore" :state="state" @reload="loadmore" />
          </view>
        </wd-tab>
        <wd-tab title="已出库">
          <view class="order-list">
            <view
              class="order-card"
              v-for="(item, index) in inSockProductData"
              :key="item.id"
              @tap="productDetail(item)"
            >
              <view class="card-header">
                <view class="order-info">
                  <text class="order-number">{{ item.code }}</text>
                  <view class="order-tag" type="warning" v-if="item.status === 2">待出库</view>
                  <view class="order-tag" type="warning" v-if="item.status === 4">部分出库</view>
                  <view class="order-tag" type="success" v-if="item.status === 5">已完成</view>
                </view>
                <view class="order-time">
                  {{
                    outStockTypeList.filter((ele) => ele.codeValue == item.reason)?.[0]?.codeName ||
                    ''
                  }}
                </view>
              </view>
              <view class="card-content">
                <view class="product-list">
                  <view
                    class="product-info"
                    v-for="(product, productIndex) in item.stockTranDetailList"
                    :key="product.id"
                  >
                    <view class="product-details">
                      <view class="product-name">{{ product.productName }}</view>
                      <view class="product-quantity">
                        <wd-text :text="`${product.qty} ${formatUnit(product.unit)}`"></wd-text>
                      </view>
                      <!-- <view class="location-info">
                        <wd-icon name="location" size="14" color="#666666"></wd-icon>
                        <text class="location-text">{{ product.location }}</text>
                      </view> -->
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <wd-loadmore custom-class="loadmore" :state="state" @reload="loadmore" />
          </view>
        </wd-tab>
      </wd-tabs>
    </scroll-view>
  </view>
  <scan-code @scanSuccess="getScanData"></scan-code>
  <!-- <wd-button @tap="getScanData('TOUT2025031400000002')">测试</wd-button> -->
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import scanCode from '@/components/scanCode/scanCode.vue'
import { useMessage, useToast } from 'wot-design-uni'
import inOrOutStockApi, { TransferData } from '@/api/inOrOutStock'
import { LoadMoreState } from 'wot-design-uni/components/wd-loadmore/types'
import { ScanPatternType } from '@/api/scanCode'
import { formatUnit } from '@/utils/unit'
import configApi, { ConfigData, ConfigType } from '@/api/config'
import myPicker from '@/components/selectPicker/myPicker.vue'

const state = ref<LoadMoreState>('loading')
const queryCode = ref('')

const tab = ref<number>(0)
const toast = useToast()

// 下拉刷新
const isRefreshing = ref(false)
const onRefresh = () => {
  isRefreshing.value = true
  console.log('下拉刷新')
  setTimeout(() => {
    changeTabs()
    isRefreshing.value = false
  }, 1000)
}
const getScanData = (e) => {
  console.log('扫码结果：', e)

  // 如果扫码结果已TOUT开头，长度20位，则认为是出库单
  if (ScanPatternType.OUTBOUND_ORDER.test(e)) {
    selectOutSockChange(e)
  } else {
    toast.warning('请扫描正确的出库单')
  }
}
// 定义每次请求页码
const queryPage = reactive({
  pageNum: 1,
  pageSize: 10,
  code: '',
  statusList: [2, 4],
  iocode: 'o',
})
const total = ref<number>(0)
const hasNextPage = ref<boolean>(true)
const inSockProductData = ref<TransferData[]>([])
const selectOutSockChange = (e) => {
  console.log(e, 'e.value')

  inSockProductData.value = []
  queryCode.value = e.value
  queryPage.code = e.value
  getInSockProduct()
}

const selectOutSockClear = () => {
  queryPage.code = ''
  inSockProductData.value = []
  getInSockProduct()
}
// 获取出库信息
const getInSockProduct = () => {
  // 请求接口
  inOrOutStockApi
    .getTStockTranHeadList({
      ...queryPage,
    })
    .then((res: any) => {
      console.log(res, '出库信息')
      total.value = res.data.total
      hasNextPage.value = res.data.hasNextPage
      inSockProductData.value.push(...res.data.list)

      state.value = 'finished'
    })
    .catch((err) => {
      state.value = 'error'
      console.log(err)
    })
}

// 触底加载更多
onReachBottom(() => {
  if (hasNextPage.value) {
    state.value = 'loading'
    loadmore()
  } else {
    state.value = 'finished'
  }
})
function loadmore() {
  queryPage.pageNum++
  if (tab.value === 0) {
    // tab.value = '待出库'
    queryPage.statusList = [2, 4]
    getInSockProduct()
  } else if (tab.value === 1) {
    // tab.value = '已出库'
    queryPage.statusList = [5]
    getInSockProduct()
  }
}
// 进入详情页
const productDetail = (item) => {
  queryCode.value = ''
  // selectOutSockClear()
  uni.navigateTo({
    url: `/pages/outOfStock/detail?outCode=${item.code}`,
  })
}

// 切换tabs
function changeTabs() {
  console.log(tab.value)
  queryPage.pageNum = 1
  inSockProductData.value = []
  state.value = 'loading'
  if (tab.value === 0) {
    queryPage.statusList = [2, 4]
    getInSockProduct()
  } else if (tab.value === 1) {
    queryPage.statusList = [5]
    getInSockProduct()
  }
}
const outStockTypeList = ref<ConfigData[]>([])
// 获取配置信息
const getOutStockType = () => {
  configApi.getConfigInfo(ConfigType.TRAN_OUT_REASON).then((res) => {
    outStockTypeList.value = res.data
  })
}
onLoad(() => {
  queryPage.statusList = [2, 4]
  getInSockProduct()

  getOutStockType()
})

// 下拉刷新
onPullDownRefresh(() => {
  console.log('下拉刷新')

  uni.startPullDownRefresh({
    success() {},
    complete() {
      uni.stopPullDownRefresh()
    },
  })
})

onShow(() => {
  uni.startPullDownRefresh({
    success() {},
    complete() {
      setTimeout(() => {
        uni.stopPullDownRefresh()
      }, 3000)
    },
  })
})

// 页面隐藏注销事件
onHide(() => {})
</script>
<style lang="scss" scoped>
$primary-color: #3e7bfa;
$secondary-color: #36b8c2;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$background-color: #f5f7fa;
$card-background: #ffffff;
$text-primary: #303133;
$text-secondary: #606266;
$border-color: #ebeef5;
$box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

page {
  width: 100%;
  height: 100%;
  .wot-theme-light {
    height: 100%;
    background-color: $background-color;
  }
}
// 更新主题变量

.page-container {
  height: 100%;
  // padding-bottom: env(safe-area-inset-bottom);
  background-color: $background-color;
}

// 搜索区域优化
.search-section {
  background: linear-gradient(135deg, #f5f7fa 0%, #e9eff5 100%);

  .custom-picker {
    :deep(.wd-picker__field) {
      padding: 20rpx 28rpx;
      background: rgba(255, 255, 255, 0.95);
      border-radius: 16rpx;
      box-shadow: 0 8rpx 24rpx rgba(62, 123, 250, 0.12);
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      &:active {
        transform: scale(0.98);
      }

      .wd-input__inner {
        font-size: 30rpx;
        color: #2c3e50;
      }

      .wd-icon-arrow-down {
        color: $primary-color;
      }
    }
  }
}
.order-list {
  flex: 1;
  padding: 24rpx 32rpx;
  overflow: auto;

  .order-card {
    margin-bottom: 24rpx;
    background-color: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.02);
    border-radius: 20rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
    .card-header {
      padding: 24rpx;
      border-bottom: 1px solid #f5f5f5;

      .order-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 8rpx;
        .order-number {
          margin-right: 16rpx;
          font-size: 15px;
          font-weight: 500;
          color: #333333;
        }
        .order-tag {
          // padding: 6rpx 16rpx;
          // font-size: 12px;
          // font-weight: 500;
          padding: 6rpx 20rpx !important;
          font-size: 24rpx !important;
          font-weight: 500;
          letter-spacing: 1rpx;
          border-radius: 8rpx !important;

          &[type='warning'] {
            color: $danger-color;
            background: rgba($warning-color, 0.15) !important;
            border: 1rpx solid rgba($warning-color, 0.3);
          }

          // 已完成状态
          &[type='success'] {
            color: $success-color;
            background: rgba($success-color, 0.15) !important;
            border: 1rpx solid rgba($success-color, 0.3);
          }
        }
      }
      .order-time {
        font-size: 12px;
        color: #999999;
      }
    }
    .card-content {
      padding: 24rpx;

      .product-list {
        display: flex;
        flex-direction: column;
        .product-info {
          display: flex;

          width: 100%;
          padding: 24rpx 0;
          .product-details {
            // flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;

            .product-name {
              overflow: hidden;
              font-size: 15px;
              font-weight: 500;
              color: #333333;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .product-quantity {
              font-size: 13px;
              color: #666666;
            }
            .location-info {
              display: flex;
              align-items: center;

              .location-text {
                margin-left: 8rpx;
                font-size: 13px;
                color: #666666;
              }
            }
          }
        }
      }
    }
  }

  .order-card:hover {
    box-shadow: 0 12rpx 48rpx rgba(0, 0, 0, 0.08);
    transform: translateY(-2rpx);
  }
}
// Tabs优化
.custom-tabs {
  :deep(.wd-tabs__nav) {
    // padding: 0 24rpx;
    background: transparent;

    .wd-tabs__nav-item {
      position: relative;
      padding: 24rpx 0;
      margin: 0 32rpx;
      transition: color 0.3s;

      &::after {
        position: absolute;
        bottom: 0;
        left: 50%;
        width: 0;
        height: 6rpx;
        content: '';
        background: $primary-color;
        transition: all 0.3s;
      }

      &.is-active {
        font-weight: 600;
        color: $primary-color;

        &::after {
          left: 0;
          width: 100%;
        }
      }
    }

    .wd-tabs__line {
      display: none;
    }
  }
}

// 状态标签优化
.status-tag {
  padding: 6rpx 20rpx !important;
  font-size: 24rpx !important;
  font-weight: 500;
  letter-spacing: 1rpx;
  border-radius: 8rpx !important;
}

// 单元格样式优化
.wd-cell {
  overflow: hidden;
  background: rgba($background-color, 0.6);
  border-radius: 16rpx;
  transition: all 0.3s;

  &:active {
    background: rgba($primary-color, 0.05);
  }

  :deep(.wd-text) {
    &[color='#36B8C2'] {
      font-weight: 500;
    }
  }
}

// 删除按钮优化
// 滑动删除按钮优化
.delete-btn {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  margin: 0 24rpx;
  overflow: hidden;
}

// 加载更多样式
.loadmore {
  :deep(.wd-loadmore__text) {
    position: relative;
    padding-left: 48rpx;
  }
}

@keyframes spin {
  to {
    transform: translateY(-50%) rotate(360deg);
  }
}

// 分割线优化
.wd-divider {
  margin: 24rpx 0;
  background-color: rgba($border-color, 0.6);
}

// 新增动画效果
@keyframes cardEntrance {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.wd-swipe-action {
  animation: cardEntrance 0.4s ease-out both;
}

// 重量显示优化
.weight-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 24rpx;

  background: rgba($primary-color, 0.05);
  border-radius: 16rpx;

  .weight-value {
    font-family: DIN Alternate;
    font-size: 48rpx;
    font-weight: 700;
    color: $primary-color;
  }

  .unit {
    margin-left: 16rpx;
    font-size: 28rpx;
    color: $text-secondary;
  }
}

// 操作按钮组优化
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 24rpx;

  .action-btn {
    border-radius: 16rpx;
    box-shadow: $box-shadow;
    transition: all 0.3s;

    &:active {
      opacity: 0.9;
      transform: scale(0.98);
    }
  }
}

// 骨架屏加载优化
@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

.skeleton-item {
  margin-bottom: 24rpx;
  background: linear-gradient(
    90deg,
    rgba($background-color, 0.8) 25%,
    rgba($background-color, 0.9) 50%,
    rgba($background-color, 0.8) 75%
  );
  background-size: 200% 100%;
  border-radius: 16rpx;
  animation: shimmer 1.5s infinite;
}
</style>
